package com.wxy.service.serviceimpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wxy.dao.BookDao;
import com.wxy.dao.BorrowRecordDao;
import com.wxy.dao.UserBookDao;
import com.wxy.dao.UserDao;
import com.wxy.domain.*;
import com.wxy.service.ManagerService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 47868
 */
@Service("ManagerService")
public class ManagerServiceImpl implements ManagerService {
    private final BorrowRecordDao borrowRecordDao;
    private final UserDao userDao;
    private final UserBookDao userBookDao;
    private final BookDao bookDao;
    private final RestHighLevelClient client;
    public static final String NULL="null";
    @Autowired
    public ManagerServiceImpl(BorrowRecordDao borrowRecordDao,
                              UserDao userDao,
                              UserBookDao userBookDao,
                              BookDao bookDao,
                              RestHighLevelClient client) {
        this.borrowRecordDao = borrowRecordDao;
        this.userDao = userDao;
        this.userBookDao = userBookDao;
        this.bookDao = bookDao;
        this.client = client;
    }

    @Override
    public R getAllBorrowInfo(String searchTerm) {
        List<BorrowRecord> borrowRecords;
        List<ManagerBorrow_Info> managerBorrowInfos=new ArrayList<>();
        //没有查询条件
        if(NULL.equals(searchTerm)){
            borrowRecords = borrowRecordDao.selectList(null);
            for (BorrowRecord borrowRecord : borrowRecords) {
                ManagerBorrow_Info managerBorrowInfo= BeanUtil.toBean(borrowRecord, ManagerBorrow_Info.class);
                managerBorrowInfos.add(managerBorrowInfo);
            }
            return R.ok("查询成功",managerBorrowInfos);
        }
        //可以根据书名搜索
        borrowRecords=borrowRecordDao.selectList(new QueryWrapper<BorrowRecord>().eq("bookname",searchTerm));
        //判空
        if(borrowRecords!=null&& !borrowRecords.isEmpty()){
            for (BorrowRecord borrowRecord : borrowRecords) {
                ManagerBorrow_Info borrowInfo= BeanUtil.toBean(borrowRecord, ManagerBorrow_Info.class);
                managerBorrowInfos.add(borrowInfo);
            }
            return R.ok("查询成功",managerBorrowInfos);
        }
        //可以根据用户名搜索
        User user=userDao.selectOne(new QueryWrapper<User>().eq("username",searchTerm).select("card_id"));
        if(user==null){
            return R.ok("查询成功",managerBorrowInfos);
        }
        Long uid=user.getCardId();
        borrowRecords=borrowRecordDao.selectList(new QueryWrapper<BorrowRecord>().eq("uid",uid));
        for (BorrowRecord borrowRecord : borrowRecords) {
            ManagerBorrow_Info borrowInfo = BeanUtil.toBean(borrowRecord, ManagerBorrow_Info.class);
            managerBorrowInfos.add(borrowInfo);
        }
        return R.ok("查询成功",managerBorrowInfos);
    }

    @Override
    public R getAllUser(String searchTerm) {
        List<User> users=userDao.selectList(null);
        List<UserBookNum> userBookNums = userBookDao.selectList(null);
        List<User_Info> userInfos=new ArrayList<>();
        //判断是否传入参数
        if(NULL.equals(searchTerm)){
            if(users==null){
                return R.ok("查询成功",userInfos);
            }
            //返回所有用户数据
            int i=0;
            for (User user : users) {
                User_Info userInfo=BeanUtil.toBean(user, User_Info.class);
                int bookNum=userBookNums.get(i).getNums();
                userInfo.setNums(bookNum);
                userInfos.add(userInfo);
                i++;
            }
            return R.ok("查询成功",userInfos);
        }
        //前端指定查询用户数据
        User user=userDao.selectOne(new QueryWrapper<User>().eq("username",searchTerm));
        if(user==null){
            return R.ok("查询成功",userInfos);
        }
        Long uid=user.getCardId();
        int bookNum=userBookDao.selectOne(new QueryWrapper<UserBookNum>().eq("uid",uid)).getNums();
        User_Info userInfo=BeanUtil.toBean(user, User_Info.class);
        userInfo.setNums(bookNum);
        userInfos.add(userInfo);
        return R.ok("查询成功",userInfos);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R addBook(String bookName, String author, int num) {
        try {
            int dataSourceId=bookDao.getMaxBookNum()+1;
            bookDao.insert(new Book(dataSourceId,bookName,author,num));
            IndexRequest request=new IndexRequest("book").id(Integer.toString(dataSourceId-10000));
            Map<String,Object> map=new HashMap<>();
            map.put("bid",dataSourceId);
            map.put("bookName",bookName);
            map.put("author",author);
            map.put("nums",num);
            request.source(JSONUtil.toJsonStr(map), XContentType.JSON);
            client.index(request, RequestOptions.DEFAULT);
            return R.ok("添加成功");
        }
        catch (Exception e) {
            throw new MyException(e.getMessage());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R deleteBook(int bid) {
        try {
            if(borrowRecordDao.exists(new QueryWrapper<BorrowRecord>().eq("bid",bid).eq("status","未还"))){
                return R.error(403,"该书籍还有用户未还，您没有权限删除...");
            }
            bookDao.deleteById(bid);
            DeleteRequest request=new DeleteRequest("book").id(Integer.toString(bid-10000));
            client.delete(request, RequestOptions.DEFAULT);
            return R.ok("删除成功");
        }
        catch (Exception e) {
            throw new MyException(e.getMessage());
        }
    }

}
